package com.yaoxiaowen.project2.test.database.test_realm;



import com.yaoxiaowen.project2.util.log.debug.LogInterface;
import com.yaoxiaowen.project2.util.log.debug.LogTool;

import java.util.List;

import io.realm.Realm;
import io.realm.RealmModel;
import io.realm.RealmObject;

/**
 * YaoWen(43194) create at tongcheng work pc,
 * time:  2017/1/20 16:11  qq:2669932513
 *
 * Notice:
 * 1,在使用之后，请注意条用 close 方法
 */
public class DbBaseHelper<E extends  RealmModel> {
    private volatile static DbBaseHelper INSTANCE = null;

    Realm realm = null;

    public static final String TAG = "DbBaseHelper";
    private static final LogInterface mLog = LogTool.getLogType();
    private static final boolean DEBUG = true;


    public DbBaseHelper() {
        realm = Realm.getDefaultInstance();
    }

    public  Realm getRealm(){
        return realm;
    }



    public List<E> findAll(Class clazz){
        List<E> list;
        try {
            list = realm.where(clazz).findAll();
            return list;
        }catch (Exception e){
            mLog.e(TAG, "findAll() " + clazz + "\t  查找发生错误");
            e.printStackTrace();
        }
        
        return  null;
    }

    public void saveJson(Class clazz, String json){
        realm.beginTransaction();
        try {
            realm.createAllFromJson(clazz, json);
            realm.commitTransaction();
        } catch (Exception e) {
            mLog.e(TAG, "saveJson() " + clazz + "\t 存储发生错误");
            realm.cancelTransaction();
            e.printStackTrace();
        }
    }


    public void saveData(Iterable<? extends RealmModel> list){

        realm.beginTransaction();
        try {
            realm.copyToRealm(list);
            realm.commitTransaction();
        } catch (Exception e) {
            mLog.e(TAG, "saveData( list) " +  "\t 存储发生错误");
            realm.cancelTransaction();
            e.printStackTrace();
        }
    }

    public void saveData(E obj){
        realm.beginTransaction();
        try {
            realm.copyToRealm(obj);
            realm.commitTransaction();
        } catch (Exception e) {
            mLog.e(TAG, "saveData( obj) " +  "\t 存储发生错误");
            realm.cancelTransaction();
            e.printStackTrace();
        }
    }

    /**
     * 保存或更新数据库的 对象数据
     * @param obj
     */
    public void saveOrUpdate(RealmObject obj){

        realm.beginTransaction();
        try {
            realm.copyToRealmOrUpdate(obj);
            realm.commitTransaction();
        } catch (Exception e) {
            mLog.e(TAG, "saveData( obj) " +  "\t 存储发生错误");
            realm.cancelTransaction();
            e.printStackTrace();
        }
    }

    public void delete(Class<? extends RealmModel> clazz){

        realm.beginTransaction();
        realm.delete(clazz);
        realm.commitTransaction();
        close();
    }


    public void close(){
        realm.close();
        realm = null;
    }
}
